<!--
 * @Author: your name
 * @Date: 2020-11-04 20:41:30
 * @LastEditTime: 2021-06-02 10:53:14
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \ws-shop\src\components\WsCategory.vue
-->
<template>
  <div class="cate">
    <van-list
      v-model="loading"
      :finished="isEnd"
      finished-text="没有更多了"
      @load="getData"
    >
      <van-cell
        v-for="shop in cateList"
        :key="`shop-${shop.id}`"
      >
        <template #title>
          <WsCateItem
            :id="shop.id"
            :title="shop.title"
            :image="shop.image"
            :price="shop.price"
            :saleNum="shop.saleNum"
            :type="shop.type"
          />
        </template>
      </van-cell>
    </van-list>
    <div class="gotop" v-show="gotop" @click="toTop">Top</div>
  </div>
</template>

<script>
import WsCateItem from './WsCateItem'
export default {
  name: 'Category',
  data () {
    return {
      id: '',
      cateList: [],
      start: 0,
      isEnd: false,
      loading: false,
      // 节流,是否正在加载，如果正在加载不允许发送重复的请求,
      gotop: false
    }
  },
  components: {
    WsCateItem
  },
  created () {
    // 初次渲染的时候id就有了
    this.id = this.$route.params.id
    // 因为使用的van-list组件会默认发一次请求，所以这里不用再发，否则出现两次start0
    // this.getData()
  },
  // 切换的时候获取id用导航守卫
  beforeRouteUpdate (to, from, next) {
    this.id = to.params.id
    next()
    // 先把start重置为0，cateList清空
    this.start = 0
    this.cateList = []
    this.getData()
  },
  mounted () {
    window.addEventListener('scroll', this.handleScroll, true)
  },
  methods: {
    getData () {
      this.$http.getCategory(this.id, this.start)
        .then(resp => {
          const { list, nextIndex, isEnd } = resp.items
          // this.cateList.push(...resp.items.list)
          this.cateList = this.cateList.concat(list)
          this.cateList = this.cateList.filter(function (e) { return e.type === 1 })
          // this.cateList = [...this.cateList, ...resp.items.list]
          this.start = nextIndex
          this.isEnd = isEnd
          this.loading = false
        })
    },
    toTop () {
      location.reload()
    },
    handleScroll (e) {
      if (e.target.scrollTop > 300) {
        this.gotop = true
      } else {
        this.gotop = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.cate {
  .van-list {
    display: flex;
    flex-wrap: wrap;
  }
  .van-cell {
    font-size: 12px;
    line-height: 2;
    width: 46%;
    /* box-sizing: border-box; */
    margin: 2%;
    padding: 2%;
    color: #666;
    background-color: #fff;
    border-radius: 1%;
  }
  .van-cell__title {
    width: 100%;
  }
}
.gotop {
  text-align: center;
  position: fixed;
  right: 15px;
  bottom: 60px;
  cursor: pointer;
  padding: 10px;
  border-radius: 50%;
  background: lightskyblue;
  color: white;
}
</style>
